#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on Jul 25, 2014, by Junn
#

from django.contrib import admin
from regards.models import Regard, DateTip, NewRegardMessage, SystemMsg
from django.template.response import TemplateResponse
from django.core.exceptions import PermissionDenied
from utils import http, logs
import settings
import datetime

def set_regards_sent(modeladmin, request, queryset):
    '''设置问候为已发送'''
    queryset.filter(status='C').update(status='S')

def set_regards_checked(modeladmin, request, queryset):
    queryset.filter(is_checked=False).update(is_checked=True)
    
def set_regards_unsent(modeladmin, request, queryset):
    '''设置问候为未发送'''
    queryset.filter(status='S').update(status='C')

def set_regards_unchecked(modeladmin, request, queryset):
    queryset.filter(is_checked=True).update(is_checked=False)
    
set_regards_sent.short_description = u'设置[已发送]'    
set_regards_checked.short_description = u'设置[已读]'    
set_regards_unsent.short_description = u'设置[未发送]'    
set_regards_unchecked.short_description = u'设置[未读]'


class RegardAdmin(admin.ModelAdmin):
    list_display = ('id', 'author', 'family', 'receiver', 'aud', 'aud_len', 'info', 
                    'pic', 'type', 'status', 'is_sent_now', 'is_checked', 'sent_time', 'created_time') 
    search_fields = ('family', 'author__nickname', 'receiver', 'sent_time', 'created_time', 'info')
    list_filter = ('type', 'status', 'is_sent_now')  
    #fields = ('family', 'author', 'info', 'pic', 'aud', 'aud_len')     #fields for creating new item
    ordering = ('-created_time', )     
    
    actions = (set_regards_sent, set_regards_checked, set_regards_unsent, set_regards_unchecked)
 
    
########## DateTipAdmin    
def set_datetip_triggered(modeladmin, request, queryset):
    queryset.filter(is_triggered=False).update(is_triggered=True)
    
def set_datetip_untriggered(modeladmin, request, queryset):
    queryset.filter(is_triggered=True).update(is_triggered=False)
        
set_datetip_triggered.short_description = u'设置为[已触发]'   
set_datetip_untriggered.short_description = u'设置为[未触发]'   
    
class DateTipAdmin(admin.ModelAdmin):
    list_display = ('title', 'spec_date', 'notice_type', 'creator', 'is_triggered', 'is_checked', 'desc', 'created_time') 
    search_fields = ('title', 'creator__nickname', 'desc')
    list_filter = ('notice_type', 'is_triggered', 'is_checked')  
    #fields = ('family', 'author', 'info', 'pic', 'aud', 'aud_len')     #fields for creating new item
    ordering = ('creator', 'title', '-created_time', )     
    
    actions = (set_datetip_triggered, set_datetip_untriggered)
    
    
########## SystemMsgAdmin    
def set_systemmsg_checked(modeladmin, request, queryset):
    queryset.filter(is_checked=False).update(is_checked=True)
    
def set_systemmsg_unchecked(modeladmin, request, queryset):
    queryset.filter(is_checked=True).update(is_checked=False)
        
set_systemmsg_checked.short_description = u'设置为[已读]'   
set_systemmsg_unchecked.short_description = u'设置为[未读]'   
    
class SystemMsgAdmin(admin.ModelAdmin):
    list_display = ('title', 'desc', 'receiver', 'is_checked', 'created_time', 'type') 
    search_fields = ('title', 'desc', 'receiver')
    list_filter = ('is_checked', 'type')  
    ordering = ('-created_time', 'title', )     
    
    actions = (set_systemmsg_checked, set_systemmsg_unchecked)  
    
    def save_model(self, request, obj, form, change):
        '''重写该方法, 当添加系统消息时向消息队列写入新的待推送消息'''
        if not change: #新增数据
            try:
                nrmsg, created = NewRegardMessage.objects.get_or_create(
                    sender=settings.SYS_ADMIN, msg_type='S'
                )
                nrmsg.set_extra_info(1, 'S', obj.title, datetime.datetime.now())
            except Exception, e:
                logs.warn('SystemMsgAdmin.save_model:  %s' % e)
                pass 
        #else:  # 修改数据   
        #    pass
        obj.save()
    
#     def get_urls(self):
#         from django.conf.urls import patterns, url
#         return patterns('',
#             url(r'^add_sys_message/$', self.admin_site.admin_view(self.add_sys_message), name="add_sys_message"),
#         ) + super(SystemMsgAdmin, self).get_urls()
    
    
#     def add_sys_message(self, request):
#         if not self.has_change_permission(request):
#             raise PermissionDenied
#         if request.method == "POST":
#             return http.ok()  #test
#             
#         return upload_template_response(request, self)
    
# def upload_template_response(req, admin_model):
#     return TemplateResponse(req, 'admin/add_system_message.html',
#                                 context={'opts': admin_model.model._meta},
#                                 current_app=admin_model.admin_site.name)
    
    
########## NewRegardMessageAdmin    
def set_msg_pushed(modeladmin, request, queryset):
    queryset.filter(is_pushed=False).update(is_pushed=True)
    
def set_msg_unpushed(modeladmin, request, queryset):
    queryset.filter(is_pushed=True).update(is_pushed=False)
    
set_msg_pushed.short_description = u'设置为[已推送]'
set_msg_unpushed.short_description = u'设置为[未推送]'
    
class NewRegardMessageAdmin(admin.ModelAdmin):
    list_display = ('id', 'msg_type', 'sender', 'receiver', 'is_pushed', 'count', 
                    'pushed_err_count', 'updated_time')
    search_fields = ('id', 'sender', 'receiver')
    list_filter = ('msg_type', 'is_pushed',)  
    #fields = ('family', 'author', 'info', 'pic', 'aud', 'aud_len')     #fields for creating new item
    ordering = ('-msg_type', 'sender', 'receiver','-updated_time', )
    
    actions = (set_msg_pushed, set_msg_unpushed)
    
    
admin.site.register(Regard, RegardAdmin)
admin.site.register(DateTip, DateTipAdmin)
admin.site.register(SystemMsg, SystemMsgAdmin)

admin.site.register(NewRegardMessage, NewRegardMessageAdmin)

